package com.kly.user.utils;

import com.alibaba.fastjson.JSONObject;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.user.config.NacosValueConfig;
import okhttp3.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

@Component
public class FeishuPushUtil {
    private static final Log logger = LogFactory.getLog(FeishuPushUtil.class);
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    @Resource
    private NacosValueConfig nacosValueConfig;

    public void sendTextMessage(String text) {
        if (!nacosValueConfig.feishuPushSwitch()) {
            logger.info("==FeishuTaskBase 发送给飞书的报警开关未打开  ==");
            return;
        }
        logger.info(">>>>>>>>>>>>飞书消息通知发送开始 {},", text);

        String json = String.format("{\"msg_type\": \"text\", \"content\": {\"text\": \"%s\"}}}", text);

        try {
            String resp = LittleOrangeService.post(nacosValueConfig.feishuWebhookApi(), "c51e5ac8-6cf1-41cb-9e3c-3d645259103d", json);
            logger.info(">>>>>>>>>>>>飞书消息通知发送结束 {}, {}", text, resp);
        } catch (Exception ex) {
            logger.info(">>>>>>>>>>>>飞书消息通知发送失败 {}", text, ex);
        }
    }

    public void sendTextMessage2(String text) {
        if (!nacosValueConfig.feishuPushSwitch()) {
            logger.info("==FeishuTaskBase 发送给飞书的报警开关未打开  ==");
            return;
        }
        logger.info(">>>>>>>>>>>>飞书消息通知发送开始 {},", text);
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .build();
        String json = String.format("{\"msg_type\": \"text\", \"content\": {\"text\": \"%s\"}}}", text);
        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
                .url(nacosValueConfig.feishuWebhookApi())
                .post(body)
                .build();
        try {
            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                logger.info(">>>>>>>>>>>>飞书消息通知发送成功 {}, {}", text, JSONObject.toJSONString(response));
                return;
            }
            logger.info(">>>>>>>>>>>>飞书消息通知发送失败 {}, {}", text, JSONObject.toJSONString(response));
        } catch (Exception ex) {
            logger.info(">>>>>>>>>>>>飞书消息通知发送失败 {}", text, ex);
        }
    }
}
